package com.cqfae.deploycentral.app.web.controller;

import com.cqfae.deploycentral.app.utils.GsonUtils;
import com.cqfae.deploycentral.app.base.BaseConstantCode;
import com.cqfae.deploycentral.app.base.BaseConstants;
import com.cqfae.deploycentral.app.services.ApproveDocumentService;
import com.cqfae.deploycentral.app.services.CommonControllerService;
import com.cqfae.deploycentral.app.utils.CheckFileTypeUtil;
import com.cqfae.deploycentral.app.utils.NullUtil;
import com.cqfae.deploycentral.app.web.request.ApproveDocumentRequest;
import com.cqfae.deploycentral.app.web.request.ApproverRequest;
import com.cqfae.deploycentral.app.web.request.ReportInfoRequest;
import com.cqfae.deploycentral.app.web.response.WebResponse;
import com.cqfae.deploycentral.app.web.vo.ApproveFilesVo;
import com.cqfae.deploycentral.app.web.vo.ApproveInfoVo;
import com.cqfae.deploycentral.app.web.vo.SelectedVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.cqfae.deploycentral.app.base.BaseConstantCode.APPROVE_STATUS_FAIL_CODE;
import static org.springframework.util.Assert.isTrue;

@RestController
@RequestMapping("/deploy-central/approve")
public class ApproveDocumentController implements CommonControllerService<Object>{

    private static Logger logger = LoggerFactory.getLogger(ApproveDocumentController.class);

    @Autowired
    private ApproveDocumentService approveDocumentService;
    @Autowired
    private CheckFileTypeUtil checkFileTypeUtil;



    /**
     * 开发查询所有需要审批的项目信息
     * @return WebResponse
     */
    @RequestMapping(value = "/info")
    public WebResponse pageInfo(ApproveDocumentRequest request) {
        logger.info("==== pageInfo ReportInfoRequest :==== {}", GsonUtils.getInstance().toJson(request));
        return getWebResponse(approveDocumentService.dispalyWhitPage(request,"develop"));
    }

    /**
     * 运维查询所有需要审批的项目信息
     * @return WebResponse
     */
    @RequestMapping(value = "/infoForOperation")
    public WebResponse pageInfoForOperation(ApproveDocumentRequest request) {
        logger.info("==== pageInfo ReportInfoRequest :==== {}", GsonUtils.getInstance().toJson(request));
        return getWebResponse(approveDocumentService.dispalyWhitPage(request,"operation"));
    }
    /**
     * 查询所有需要审批的项目信息
     * @return WebResponse
     */
    @RequestMapping(value = "/unChecked")
    public WebResponse unChecked() {
        int unChecked = approveDocumentService.readedNumber();
        logger.info("==== isNotReadNum is :==== {}", GsonUtils.getInstance().toJson(unChecked));
        return getWebResponse(unChecked);
    }

    /**
     * 根据
     * @return WebResponse
     */
    @RequestMapping(value = "/infoOne")
    public WebResponse infoOne(ApproveDocumentRequest request) {
        logger.info("==== infoOne ReportInfoRequest :==== {}", GsonUtils.getInstance().toJson(request));
        return getWebResponse(approveDocumentService.getInfoByApprovedId(request));
    }


    @RequestMapping(value = "/add")
    public WebResponse addInfo(@RequestBody ApproveInfoVo approveInfoVo) {
        //SQL是否存在优先级，如果有备注必填写
        if((BaseConstantCode.APPROVE_ISACCESS_SUCCESS_CODE == approveInfoVo.getIsPriorityScript())
                && NullUtil.isEmpty(approveInfoVo.getReserved2())){
            isTrue(false, "脚本存在优先级时必须填写说明");
        }
        isTrue(NullUtil.isNotEmpty( approveInfoVo.getCode() ) && NullUtil.isNotEmpty( approveInfoVo.getName() ), "未传入应用的编号和名称");
        isTrue(NullUtil.isNotEmpty( approveInfoVo.getOnlineTime()), "未传入上线时间");
        logger.info("==== addApproveInfo ReportInfoRequest :==== {}", approveInfoVo);
        return getWebResponse(approveDocumentService.save(approveInfoVo));
    }

    /**
     * 修改：除了修改审批状态以外，还需要在返回的时候修改审批状态（已读）
     * @return WebResponse
     */
    @RequestMapping(value = "/update")
    public WebResponse updateInfo(@RequestBody ApproverRequest request) {
        if(request.getApproverStatus() == APPROVE_STATUS_FAIL_CODE && NullUtil.isEmpty(request.getRefuseInfo())){
            isTrue(false, "不同意该评审文件时请先填写原因");
        }
        logger.info("==== updateApproveInfo ReportInfoRequest :==== {}", GsonUtils.getInstance().toJson(request));
        return getWebResponse(approveDocumentService.updateApprove(request));
    }

    @RequestMapping(value = "/file/upload",method = RequestMethod.POST)
    public WebResponse fileUpload(@RequestParam("file") MultipartFile file)
            throws IOException {
        isTrue( file.getSize() != 0 && file.getSize() < BaseConstants.FILE_LIMIT_BYTES,"文件上传大小必须在1k到10M之间");
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
        if(checkFileTypeUtil.jagementFileSuffix(fileSuffix,"file")){
            isTrue(false, "只支持doc、docx、xls、xlsx、ppt、pptx、pdf、jpg、png、rar、zip、properties、yaml、yml、xml、txt的类型文件");
        }
        return getWebResponse(approveDocumentService.upload(file,fileSuffix));
    }

    @RequestMapping(value = "/file/uploadWithSQL",method = RequestMethod.POST)
    public WebResponse uploadWithSQL(@RequestParam("file") MultipartFile file)
            throws IOException {
        Assert.isTrue( file.getSize() != 0 && file.getSize() < BaseConstants.FILE_LIMIT_BYTES,"文件上传大小必须在1k到10M之间");
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
        if(checkFileTypeUtil.jagementFileSuffix(fileSuffix,"sql")){
            isTrue(false, "只支持sql、zip的类型文件");
        }
        return getWebResponse(approveDocumentService.upload(file,fileSuffix));
    }

    @RequestMapping(value = "/file/download")
    public void exportFile(ApproveDocumentRequest approveDocumentRequest,HttpServletResponse response)  {
        logger.info("==== exportFile fileId :==== {}", approveDocumentRequest);
        approveDocumentService.downloadFile(approveDocumentRequest.getId(),response);
    }

    /**
     * 删除附件
     */
    @RequestMapping(value = "/file/delete",method = RequestMethod.POST)
    public WebResponse fileDelete(@RequestBody ApproveFilesVo vo)  {
        String attachmentPath = vo.getAttachmentPath();
        Long id = vo.getId();
        if(NullUtil.isNotEmpty(id) && NullUtil.isNotEmpty(attachmentPath)){
            return getWebResponse(approveDocumentService.fileDelete(id,attachmentPath));
        }else{
            logger.info("==== exportFile fileId :==== {}", attachmentPath);
        }
        return getWebResponse("0");
    }


    /**
     * 重新上传评审文件（修改非评审结果相关信息）
     */
    @RequestMapping(value = "/updateDocument")
    public WebResponse updateApproveDecumentInfo(@RequestBody ApproveInfoVo approveInfoVo) {
        logger.info("==== addApproveInfo ApproveInfoVo :==== {}", approveInfoVo);
        return getWebResponse(approveDocumentService.updateApproveDecumentInfo(approveInfoVo));
    }

    /**
     * 过滤下查出来的报告内容
     * @param request
     * @return
     */
    @RequestMapping(value = "/handReportSelected")
    public WebResponse handReportSelected(ReportInfoRequest request) {
        String requestJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== handReportSelected ReportInfoRequest :==== {}", requestJson);
        return getWebResponse(approveDocumentService.handReportSelected(request));
    }

    @RequestMapping(value = "/checkIsExistReportPlan")
    public WebResponse checkIsExistReportPlan(SelectedVo selectedVo) {
        logger.info("==== checkIsExistReportPlan:==== {}", selectedVo.getCode());
        return getWebResponse(approveDocumentService.checkIsExistReportPlan(selectedVo));
    }

    @Override
    public WebResponse getWebResponse(Object obj) {
        WebResponse webResponse = new WebResponse();
        if (NullUtil.isNotEmpty(obj)) {
            webResponse.setData(obj);
        }
        return webResponse;
    }

}
